package com.blahti.example.drag2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.icons.draw.view.*;

import data.*;

public class OpenScreen extends Activity implements LocationListener {

	final OpenScreen thisActivity = this;
	ParkingDB parking_db;
	double longitude;
	double latitude;
	String RspType="";
	int id=0;
	LocationManager lm;



	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.open_screen);
		//getWindow().setBackgroundDrawableResource(R.drawable.open_back);
		parking_db=ParkingDB.getInstance();
		Log.d("open screen","onCreate");
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
		SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
		if(!ref.getString("userSpot", "-1").equals("-1"))
		{
			parking_db.myParking=true;
			if((!ref.getString("userSpotLat", "other").equals("-1"))&&(!ref.getString("userSpotLat", "other").equals("other")))
		{
				parking_db.mySpotLat=Integer.parseInt(ref.getString("userSpotLat", "other"));
				parking_db.mySpotLong=Integer.parseInt(ref.getString("userSpotLong", "other"));
			}

		}
		if(!parking_db.serverOn)
		{
			Intent intent = new Intent(this, DrawIcons.class);
			this.startActivity(intent);
		}
		else
			performRequest("http://"+parking_db.instanceDNS+":8080/ParkApp/ParkingsSearch");
	}	


	private final Handler handler = new Handler() {  

		public void handleMessage(Message msg) {
			String result = msg.getData().getString("RESPONSE"); 
			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document doc = db.parse(new InputSource(new StringReader(result)));
				Element docEle=doc.getDocumentElement();
				NodeList nodeList = doc.getElementsByTagName("Response");

				if(nodeList != null && nodeList.getLength() > 0) {
					Element el = (Element)nodeList.item(0);
					RspType = el.getFirstChild().getNodeValue();
				}
				if(RspType.equals("parking result"))
				{
					Log.d("openScreen","response is parkingResult");
					nodeList=doc.getElementsByTagName("ParkingSpot");
					if(nodeList!=null && nodeList.getLength()>0)
					{
						for(int i = 0 ; i < nodeList.getLength();i++)
						{
							Element el = (Element)nodeList.item(i);
							longitude=getDoubleValue(el,"Longitud_A");
							latitude= getDoubleValue(el,"Latitud_A");
							Coordinate a=new Coordinate(longitude,latitude);
							longitude=getDoubleValue(el,"Longitud_B");
							latitude= getDoubleValue(el,"Latitud_B");					
							Coordinate b=new Coordinate(longitude,latitude);
							ParkingSpot ps=new ParkingSpot(a,b);
							ps.spotId=getIntegerValue(el,"SpotID");
							String status=getTextValue(el,"status");
							if(status.equals("AVAILABLE"))
								ps.parkingStatus=0;
							else if(status.equals("NOTAVAILABLE"))
								ps.parkingStatus=1;
							else
								ps.parkingStatus=2;
							ps.accuracyLevel=getIntegerValue(el,"accuracyLevel");
							ps.street=getTextValue(el,"street");
							ps.side=getTextValue(el,"side");
							ps.timeToAvailable=getTextValue(el,"timeToAvailable");
							ps.cellID= getIntegerValue(el,"CellID");
							ps.gridID=getIntegerValue(el,"gridID");
							ps.street=getTextValue(el,"street");
							ps.ParkingType=getIntegerValue(el,"type");
							ps.side=getTextValue(el,"side");
							//if((ps.spotId>28)&&(ps.spotId<40))
							//Log.d("id status",Integer.toString(ps.spotId)+" "+Integer.toString(ps.parkingStatus));
							addToVector(ps);


						}
						//	Intent intent = new Intent(thisActivity, DrawIcons.class); 
						//startActivity(intent);

						SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
						int id=Integer.parseInt(ref.getString("my_id", "0"));

						if(id==0){
							Log.d("openScreen","go to new User");
							Intent intent = new Intent(thisActivity, NewUser.class); 
							startActivity(intent);
						}
						else
						{
							Log.d("openScreen","perform login");
							PerformLogin();
							Intent intent = new Intent(thisActivity, DrawIcons.class); 
							startActivity(intent);
						}

					}					
				}
				else{

					//Toast.makeText( getApplicationContext(),result,Toast.LENGTH_LONG).show();
				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		} 
	};

	private void PerformLogin(){final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
		public String handleResponse(HttpResponse response) {    
			//StatusLine status = response.getStatusLine();        
			HttpEntity entity = response.getEntity();          
			String result = null; 
			try { 
				result = inputStreamToString(entity.getContent());

				Message message = new Message();     
				Bundle bundle = new Bundle();         
				bundle.putString("RESPONSE", result); 
				message.setData(bundle); 
				handler.sendMessage(message);  
				Log.d("new user","wirked");
			} catch (IOException e) { 
				Log.e("Class6",  " ", e); 
			} 
			return result; 
		} 
	}; 


	// create and run the thread that perform the request and handle the response
	new Thread() {                          
		@Override 
		public void run() { 
			HttpClient httpclient = new DefaultHttpClient();
			Log.d("dbURL",parking_db.instanceDNS);
			String url="http://";
			url+=parking_db.instanceDNS;
			url+=":8080/ParkApp/NewUser";
			Log.d("url is",url);
			//HttpPost httppost = new HttpPost("http://ec2-23-22-126-138.compute-1.amazonaws.com:8080/ParkApp/NewUser");
			HttpPost httppost = new HttpPost(url);
			try {
				try{
					DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

					DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();

					//creating a new instance of a DOM to build a DOM tree.
					Document doc = docBuilder.newDocument();
					Element Response = doc.createElement("MSG_TYPE");
					Response.appendChild(doc.createTextNode("LOGIN"));
					doc.appendChild(Response);

					Element type=doc.createElement("LOGIN_TYPE");
					type.appendChild(doc.createTextNode("LOGIN_NOT_NEW"));
					Response.appendChild(type);
					SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
					int myID=Integer.parseInt(ref.getString("my_id", "0"));

					Element id=doc.createElement("USER_ID");
					id.appendChild(doc.createTextNode(Integer.toString(myID)));
					type.appendChild(id);

					TransformerFactory factory = TransformerFactory.newInstance();
					Transformer transformer = factory.newTransformer();

					transformer.setOutputProperty(OutputKeys.INDENT, "yes");

					StringWriter sw = new StringWriter();
					StreamResult result = new StreamResult(sw);
					DOMSource source = new DOMSource(doc);
					transformer.transform(source, result);
					String xmlString = sw.toString();
					Log.d("xmlString","^^^^^^^^^^^^^^^^^^^^"+xmlString);


					StringEntity se = new StringEntity(xmlString); //XML as a string
					se.setContentType("text/xml"); //declare it as XML
					httppost.setEntity(se);



					String response = httpclient.execute(httppost,responseHandler);
					Log.d("","************************************* "+response);

				}
				catch (ClientProtocolException e) {
					Log.e("LOGTAG", " " , e); 
				} catch (IOException e) {
					Log.e("LOGTAG", " " , e); 
				} catch (TransformerConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}




			}
			catch(Exception e)
			{
				Log.e("LOGTAG", " " , e); 
			}
		}

	}.start(); 


	}



	private void performRequest(final String uri) { 
		// create HTTP response handler to handle the HTTP response
		// the response data is extracted from the HTTP message and then it is wrapped in a message
		// which  is passed to the android handler for handling
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = inputStreamToString(entity.getContent());   
					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);         
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 



		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(uri);
				Log.d("performRequest","works");
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();

						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Request = doc.createElement("MSG_TYPE");
						Request.appendChild(doc.createTextNode("PARK_REQUEST"));
						doc.appendChild(Request);

						Element Userid=doc.createElement("USER_ID");
						Userid.appendChild(doc.createTextNode("0"));//can be 0 on newUser!!
						Request.appendChild(Userid);


						Element longi=doc.createElement("LONGI");
						Element lati=doc.createElement("LAT");
						//longi.appendChild(doc.createTextNode(Double.toString(parking_db.curLoc.longitude)));//change to user location
						//lati.appendChild(doc.createTextNode(Double.toString(parking_db.curLoc.latitude)));//change to user location

                        int i=0;
						while((parking_db.gps==true)&&(parking_db.user_gps==true)&&(i<30))
						{
							i++;
							Log.d("DrawIcons","gps is true");
							if(parking_db.curLoc!=null)
							{
								longi.appendChild(doc.createTextNode(Double.toString(parking_db.curLoc.longitude)));
								lati.appendChild(doc.createTextNode(Double.toString(parking_db.curLoc.latitude)));
							}
						}
						if(parking_db.curLoc==null)
						{
							longi.appendChild(doc.createTextNode(Double.toString(parking_db.noGpsLoc.longitude)));
							lati.appendChild(doc.createTextNode(Double.toString(parking_db.noGpsLoc.latitude)));
						}

						Userid.appendChild(longi);
						longi.appendChild(lati);

						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString",xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);

						String response = httpclient.execute(httppost,responseHandler);
						Log.d("","*server response* "+response);
					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					}

				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 
	}


	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}

	private double getDoubleValue(Element ele, String tagName) {
		String strVal = null;
		double doubleVal=0;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			strVal = el.getFirstChild().getNodeValue();
			doubleVal=Double.parseDouble(strVal);
		}

		return doubleVal;
	}

	private int getIntegerValue(Element ele, String tagName) {
		String strVal = null;
		int intVal=0;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			strVal = el.getFirstChild().getNodeValue();
			intVal=Integer.parseInt(strVal);
		}

		return intVal;
	}

	void addToVector(ParkingSpot ps)
	{
		int i;

		for( i=0;i<parking_db.parkingVector.size();i++)
		{
			if((parking_db.parkingVector.get(i).list.get(0).street.equals(ps.street))&&(parking_db.parkingVector.get(i).list.get(0).side.equals(ps.side)))
			{
				parking_db.parkingVector.get(i).list.add(ps);
				break;
			}	
		}
		if(i==parking_db.parkingVector.size())
		{
			parking_db.parkingVector.add(new ParkingSpotsList());
			parking_db.parkingVector.elementAt(parking_db.parkingVector.size()-1).list.add(ps);

		}

	}


	public static String inputStreamToString(final InputStream stream) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = br.readLine()) != null) {
			sb.append(line + "\n");
		}
		br.close();
		return sb.toString();
	}

	public void onRestart(){
		Log.d("OpenScreen","onResume");
		super.onRestart();
		SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
		if(ref.getString("exit", "other").equals("true"))
		{
			SharedPreferences.Editor ed=ref.edit();
			ed.putString("exit", "false");
			ed.commit();
			finish();
		}

	}



	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub


		if ((location != null)&&(parking_db.gps)&&(parking_db.user_gps)) {
				double lat = location.getLatitude();
				double lng = location.getLongitude();
				if(parking_db.curLoc!=null)
				{
					parking_db.preLoc=new MapLocation("i am here",parking_db.curLoc.latitude,parking_db.curLoc.longitude);
				}	
				parking_db.curLoc=new MapLocation("i am here",lat,lng);
				handleReverseGeocodeClick();

		}
	}
	private void handleReverseGeocodeClick()
	{
		if (parking_db.curLoc != null)
		{
			// Kickoff an asynchronous task to fire the reverse geocoding
			// request off to google
			ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
			task.drawIconContext = this;
			task.execute();

		}
	}


	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		String message = "GPS Disabled ";
		parking_db.gps=false;
		Toast.makeText (getApplicationContext(), message, Toast.LENGTH_LONG).show ();
		//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);


	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		String message = "GPS Enabled ";
		parking_db.gps=true;
		Toast.makeText (getApplicationContext(), message, Toast.LENGTH_LONG).show ();
		//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);


	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	    switch (status) {
        case LocationProvider.AVAILABLE:
        	 parking_db.gps=true;
        	 break;
        case LocationProvider.OUT_OF_SERVICE:
        	 parking_db.gps=false;
             break;
        case LocationProvider.TEMPORARILY_UNAVAILABLE:
        	 parking_db.gps=false;

            break;
        }

	}
	  @Override
	    protected void onResume() {
	        super.onResume();

	        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, thisActivity);
	        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, thisActivity);
	    }

	    @Override
	    protected void onPause() {
	        super.onPause();

	        lm.removeUpdates(thisActivity);
	        lm.removeUpdates(thisActivity);
	    }

}
